<?php
class Customer {
	private $customer_id;
	private $firstname;
	private $lastname;
	private $email;
	private $telephone;
	private $fax;
	private $newsletter;
	private $customer_group_id;
    private $image;
    private $address_id;
    private $default_addressinfo  ;
    private $password;
    private $coupons  ;
    private $order_count;
    private $customer_points;
    private $birthday;
    private $grade;
    private $country_id;
    private $zone_id;
    private $district_id;





	public function __construct($registry) {
		$this->config = $registry->get('config');
		$this->db = $registry->get('db');
		$this->request = $registry->get('request');
		$this->session = $registry->get('session');
		if (isset($this->session->data['customer_id'])) {
			$customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE customer_id = '" . (int)$this->session->data['customer_id'] . "' AND status = '1'");
			if ($customer_query->num_rows) {
				$this->customer_id = $customer_query->row['customer_id'];
				$this->firstname = $customer_query->row['firstname'];
				$this->lastname = $customer_query->row['lastname'];
				$this->email = $customer_query->row['email'];
				$this->telephone = $customer_query->row['telephone'];
				$this->fax = $customer_query->row['fax'];
				$this->newsletter = $customer_query->row['newsletter'];
				$this->customer_group_id = $customer_query->row['customer_group_id'];
				$this->image = $customer_query->row['image'];
				$this->password = $customer_query->row['password'];
				$this->address_id = $customer_query->row['address_id'];
				$this->birthday =  $customer_query->row['birthday'];
				$this->grade = $customer_query->row['grade_time'];
				$this->country_id = $customer_query->row['country_id'];
				$this->zone_id =  $customer_query->row['zone_id'];
                $this->district_id= $customer_query->row['district_id'];
				//修改
				$this->default_addressinfo = $this->getAddress($this->address_id);
				$this->order_count=$this->getCustomerOrdersCount();
				$this->customer_points=$this->getCustometPoints();
				$this->coupons=$this->getCustomerCoupon();
				$this->db->query("UPDATE " . DB_PREFIX . "customer SET cart = '" . $this->db->escape(isset($this->session->data['cart']) ? serialize($this->session->data['cart']) : '') . "', wishlist = '" . $this->db->escape(isset($this->session->data['wishlist']) ? serialize($this->session->data['wishlist']) : '') . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "' WHERE customer_id = '" . (int)$this->customer_id . "'");

				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer_ip WHERE customer_id = '" . (int)$this->session->data['customer_id'] . "' AND ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "'");

				if (!$query->num_rows) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "customer_ip SET customer_id = '" . (int)$this->session->data['customer_id'] . "', ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', date_added = NOW()");
				}
			} else {
				$this->logout();
			}
		}
	}

	public function login($telephone, $password, $override = false, $customer_id = 0, $token = null) {
	    if($token)
	    {
	        $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE token='".$this->db->escape($token)."' AND status = '1'");
	    }
	    else if($customer_id >0)
	    {
	        $customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE customer_id='".(int)$customer_id."' AND status = '1'");
	    }
        else if ($override) {
			$customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE telephone = '" . $this->db->escape($telephone) . "' AND status = '1'");
		} else {
			$customer_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "customer WHERE telephone = '" . $this->db->escape($telephone) . "' AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1('" . $this->db->escape($password) . "'))))) OR password = '" . $this->db->escape(md5($password)) . "') AND status = '1' AND approved = '1'");
		}

		if ($customer_query->num_rows) {
			$this->session->data['customer_id'] = $customer_query->row['customer_id'];

			if ($customer_query->row['cart'] && is_string($customer_query->row['cart'])) {
				$cart = unserialize($customer_query->row['cart']);

				foreach ($cart as $key => $value) {
					if (!array_key_exists($key, $this->session->data['cart'])) {
						$this->session->data['cart'][$key] = $value;
					} else {
						$this->session->data['cart'][$key] += $value;
					}
				}
			}

			if ($customer_query->row['wishlist'] && is_string($customer_query->row['wishlist'])) {
				if (!isset($this->session->data['wishlist'])) {
					$this->session->data['wishlist'] = array();
				}

				$wishlist = unserialize($customer_query->row['wishlist']);

				foreach ($wishlist as $product_id) {
					if (!in_array($product_id, $this->session->data['wishlist'])) {
						$this->session->data['wishlist'][] = $product_id;
					}
				}
			}
			$this->customer_id = $customer_query->row['customer_id'];
			$this->firstname = $customer_query->row['firstname'];
			$this->lastname = $customer_query->row['lastname'];
			$this->email = $customer_query->row['email'];
			$this->telephone = $customer_query->row['telephone'];
			$this->fax = $customer_query->row['fax'];
			$this->newsletter = $customer_query->row['newsletter'];
			$this->customer_group_id = $customer_query->row['customer_group_id'];
			$this->image = $customer_query->row['image'];
			$this->password = $customer_query->row['password'];
			$this->birthday =  $customer_query->row['birthday'];
			$this->grade = $customer_query->row['grade_time'];
			$this->country_id = $customer_query->row['country_id'];
			$this->zone_id =  $customer_query->row['zone_id'];
			$this->district_id = $customer_query->row['district_id'];
			//$this->default_addressinfo = $this->getdefaultAddresse($customer_query->row['address_id']);
			//$this->coupons =

			//var_dump($this->default_addressinfo);

			/* $device_token_update = "";
			if(isset($this->request->post['device_token']))
			{
			    $device_token_update = "device_token='".$this->db->escape($this->request->post['device_token'])."',";
			}

			$this->db->query("UPDATE " . DB_PREFIX . "customer SET ".$device_token_update."ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "' WHERE customer_id = '" . (int)$this->customer_id . "'");
            */
			return true;
		} else {
			return false;
		}
	}



	public function loginById($customer_id)
	{
	    return $this->login("", "",false,$customer_id);
	}

	public function loginByToken($token)
	{
	    return $this->login("", "",false,0,$token);
	}

	public function logout() {
		$this->db->query("UPDATE " . DB_PREFIX . "customer SET cart = '" . $this->db->escape(isset($this->session->data['cart']) ? serialize($this->session->data['cart']) : '') . "', wishlist = '" . $this->db->escape(isset($this->session->data['wishlist']) ? serialize($this->session->data['wishlist']) : '') . "' WHERE customer_id = '" . (int)$this->customer_id . "'");

		unset($this->session->data['customer_id']);

		$this->customer_id = '';
		$this->firstname = '';
		$this->lastname = '';
		$this->email = '';
		$this->telephone = '';
		$this->fax = '';
		$this->newsletter = '';
		$this->customer_group_id = '';
		$this->image = '';
		$this->newsletter='';
		$this->default_addressinfo = array();
		$this->order_count = 0;
		$this->coupons = array();
		$this->customer_points = 0;
	}



	public function isLogged() {
		return $this->customer_id;
	}

	public function getAddressInfo(){
	    return $this->default_addressinfo;
	}

	public function getPassword() {
	    return $this->password;
	}

	public function getId() {
		return $this->customer_id;
	}



	public function getFirstName() {
		return $this->firstname;
	}

	public function getLastName() {
		return $this->lastname;
	}

	public function getEmail() {
		return $this->email;
	}

	public function getTelephone() {
		return $this->telephone;
	}

	public function getFax() {
		return $this->fax;
	}

	public function getNewsletter() {
		return $this->newsletter;
	}

	public function getPoints(){
	    return $this->customer_points;
	}

	public function getGroupId() {
		return $this->customer_group_id;
	}

	public function getAddressId() {
		return $this->address_id;
	}

	public function getDefaultAddress(){

	    return $this->default_addressinfo;
	}
	public function getBalance() {
		$query = $this->db->query("SELECT SUM(amount) AS total FROM " . DB_PREFIX . "customer_transaction WHERE customer_id = '" . (int)$this->customer_id . "'");

		return $query->row['total'];
	}



	public function getCustomerInfo()
	{
	    $customer_info = array();
	    $customer_info['customer_id'] = $this->customer_id;
	    $customer_info['name'] = $this->firstname;
	    $customer_info['lastname'] = $this->lastname;
	    $customer_info['telephone'] = $this->telephone;
	    $customer_info['image'] = $this->image;
	    $customer_info['email'] = $this->email;
	    $customer_info['default_addressinfo']=$this->default_addressinfo;
	    $customer_info['order_count']=$this->order_count;
	    $customer_info['customer_points']=$this->customer_points;
	    $customer_info['coupons']=$this->coupons;
	    $customer_info['customer_group_id']=$this->customer_group_id;
	    $customer_info['birthday']=$this->birthday ;
	    $customer_info['grade']=$this->grade ;
	    $customer_info['country_id']=$this->country_id;
	    $customer_info['zone_id']=$this->zone_id ;
        $customer_info['district_id']=$this->district_id ;
	    return $customer_info;
	}

	private function getCustomerOrdersCount(){
	    $query = $this->db->query("SELECT count(*) AS order_count FROM `" . DB_PREFIX . "order` WHERE customer_id = '" . (int)$this->customer_id . "'");
	    return $query->row['order_count'];
	}

	private function getCustomerCoupon(){
	    $query = $this->db->query("SELECT cc.is_use,cc.customer_id,cc.coupon_id,cc.num,c.* FROM " . DB_PREFIX . " customer_coupon as cc left join coupon c on cc.coupon_id = c.coupon_id  WHERE customer_id = '" . (int)$this->customer_id . "' and date_start <= now() and date_end >=now() and is_use = 0");
	    return $query->rows;
	}

	private function getCustometPoints(){
	    $query = $this->db->query("SELECT sum(points) as customer_points FROM " . DB_PREFIX . " customer_reward  WHERE customer_id = '" . (int)$this->customer_id . "'");
	    return $query->row['customer_points'];
	}
	//获取用户默认收获地址信息
	private   function getAddress($address_id)
	{

	    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$address_id . "'");

	    if($query->row){
	        return array(
	            'address_id' =>  $query->row['address_id'],
	            'customer_id' =>  $query->row['customer_id'],
	            'firstname' =>  $query->row['firstname'],
	            'lastname' =>  $query->row['lastname'],
	            'company' =>  $query->row['company'],
	            'address_1' =>  $query->row['address_1'],
	            'address_2' =>  $query->row['address_2'],
	            'city' =>  $query->row['city'],
	            'postcode' =>  $query->row['postcode'],
	            'country_id' =>  $query->row['country_id'],
	            'country' => $this->db->query("SELECT name FROM `" . DB_PREFIX . "country` WHERE country_id = '" . (int)$query->row['country_id'] . "'")->row['name'],
	            'zone_id' =>  $query->row['zone_id'],
	            'zone'  =>$this->db->query("SELECT name FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$query->row['zone_id'] . "'")->row['name'],
	            'custom_field' =>  $query->row['custom_field'],
	            'district_id' =>  $query->row['district_id'],
	            'district'  =>$this->db->query("SELECT name FROM `" . DB_PREFIX . "district` WHERE district_id = '" . (int)$query->row['district_id']. "'")->row['name'],
	            'telephone' =>  $query->row['telephone']
	        );

	    }else {
	    return array();
	    }
	}
}